<?php


namespace app\common\services;


use app\common\exception\ApiException;
use think\facade\Config;

class RedisService extends RedisCluster
{
    private static $instance = null;
    public static $status = true;
    public $redis;//操作对象

    public static function getInstance()
    {
        if(null === self::$instance){
            try{
//                $redisConfig = config('redis');
                $instance = new self();
                $redisConfig = Config::get('redis');
                //是否开启M/S 读写分离
                $isUseCluster = $redisConfig['isUseCluster'] && count($redisConfig['slave'])>0;

                $redis = new RedisCluster($isUseCluster);

                //连接主服务器
                $redis->connect($redisConfig['master'],true);
                //连接从服务器
                if($isUseCluster){
                    foreach ($redisConfig['slave'] as $itme){
                        $redis->connect($itme,false);
                    }
                }
                $instance->redis = $redis;
                self::$instance = $instance;
            } catch (\Exception $e){
                echo 'Redis Error:'. $e->getMessage()."\n\n";
//                throw new ApiException($e->getMessage());
                self::$status = $e->getMessage();
            }
        }
        return self::$instance;
    }


    /**
     * 改变后的设置值
     * @param $key
     * @param $value
     * @param $expire
     * @param false $isJson  是否使用json序列化
     */
    public function mSet($key,$value,$expire=0,$isJson=true){
        if($isJson) $value = json_encode($value);
        $this->redis->set($key,$value,$expire);
    }

    /**
     * 改版后的取值
     * @param $key
     * @param $value
     * @param false $isJson
     */
    public function mGet($key,$isJson=true){
        $val = $this->redis->get($key);
        if($val && $isJson){
            $val = json_decode($val,true);
        }
        return $val;
    }


    //防止使用new 创建多个实例
    public function __construct()
    {
    }

    //防止clone多个实例
    private function __clone()
    {
    }

    //防止反序列化
    private function __wakeup()
    {
    }

}